import { store } from '@/utils/store'
import { call } from '@/utils/request'
import { showMsg, showSuccess } from '@/utils/toast'

// const default_avatar = '/images/default_avatar.svg'
Page({
  data: {

  },
  onLoad() {

    // 为什么要用这种方式？答：为了不改变全局的user_info数据！！！！！！！
    this.setData({
      ...store.user_info,
      // avatar: store.user_info.avatar || default_avatar,
    })
  },
  onChooseAvatar(e) {
    this.setData({
      avatar: e.detail.avatarUrl,
    })
  },
  getPhoneNumber(e) {
    if (e.detail.code) {
      call('/getPhoneNumber/'+e.detail.code).then(res => {
        this.setData({
          mobile: res,
        })
      })
    }
  },
  async uploadAvatar(avatar) {
    const ext = avatar.slice(avatar.lastIndexOf('.'))
    const date = new Date();
    const path = 'avatar/' + date.getFullYear() + "/" + (date.getMonth()+1) + "/" + Date.now() + parseInt(Math.random() * 99999) + ext
    const {fileID} = await wx.cloud.uploadFile({
      cloudPath: path, // 对象存储路径，根路径直接填文件名，文件夹例子 test/文件名，不要 / 开头
      filePath: avatar, // 微信本地文件，通过选择图片，聊天文件等接口获取
      config: {
        env: 'prod-7gk926fb556e9aad' // 微信云托管环境ID
      }
    })
    return fileID
  },
  async submit() {
    const { avatar, nick_name, mobile } = this.data


    const formData = {}
    if (avatar !== store.user_info.avatar) {
      formData.avatar = await this.uploadAvatar(avatar)
    }
    if (nick_name !== store.user_info.nick_name) {
      formData.nick_name = nick_name
    }
    if (mobile !== store.user_info.mobile) {
      formData.mobile = mobile
    }
    if (Object.keys(formData).length === 0) {
      wx.navigateBack()
      return
    }


    formData.id = store.user_info.id
    await call({
      method: 'POST',
      path: '/updateUserInfo',
      data: formData
    })
    store.set_user_info(formData)
    wx.navigateBack()

  }, 

})
